package com.cn.ant.modules.wechat.web;

import com.cn.ant.common.utils.AjaxJson;
import com.cn.ant.common.utils.Identities;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.common.web.BaseController;
import com.cn.ant.modules.sys.entity.User;
import com.cn.ant.modules.sys.utils.UserUtils;
import com.cn.ant.modules.wechat.entity.MenuEntity;
import com.cn.ant.modules.wechat.entity.TextTemplate;
import com.cn.ant.modules.wechat.entity.WeiXinNewListType;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.service.MenuEntityService;
import com.cn.ant.modules.wechat.service.TextTemplateService;
import com.cn.ant.modules.wechat.service.WeiXinNewListTypeService;
import com.cn.ant.modules.wechat.service.WeixinAccountServiceImpl;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 菜单对象Controller
 * @author AntDream
 * @version 2015-03-23
 */
@Controller
@RequestMapping(value = "${adminPath}/wechat/menuEntity")
public class MenuEntityController extends BaseController {

	@Autowired
	private MenuEntityService menuEntityService;
    @Autowired
    private WeixinAccountServiceImpl accountService;
    @Autowired
    private TextTemplateService textTemplateService;
    @Autowired
    private WeiXinNewListTypeService newListTypeService;

    @ModelAttribute
	public MenuEntity get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return menuEntityService.get(id);
		}else{
			return new MenuEntity();
		}
	}

    @RequestMapping(value = "find",method = RequestMethod.POST)
    @ResponseBody
    public MenuEntity find(@RequestParam(required =  true) String id ) {
        return menuEntityService.get(id);
    }

    @RequiresPermissions("wechat:menuEntity:view")
	@RequestMapping(value = {"list", ""})
	public String list(MenuEntity menuEntity, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
        String accountId = request.getParameter("accountId");
        //查询公众号列表
        List<WeixinAccount> accountList = accountService.findByLoginUser();
        if (StringUtils.isBlank(accountId)) {
            accountId = accountList.get(0).getId();
        }
        Map<String,Object> param = new HashMap<String,Object>();
        List<MenuEntity> list = Lists.newArrayList();
        param.put("accountId", accountId);
        List<MenuEntity> sourceList = menuEntityService.queryForList(param);
        MenuEntity.sortList(list, sourceList, "1");
        model.addAttribute("list", list);
        //查询文本模板
        Map<String, Object> params = new HashMap<>();
        List<TextTemplate> textTemplateList = textTemplateService.queryForList(params);
        //查询图文模板
        List<WeiXinNewListType> newListTypeList = newListTypeService.queryByLoginUser();
        model.addAttribute("accountList", accountList);
        model.addAttribute("textTemplateList", textTemplateList);
        model.addAttribute("newListTypeList", newListTypeList);
        model.addAttribute("accountId", accountId);
        return "modules/wechat/menuEntityList";
	}

	@RequiresPermissions("wechat:menuEntity:view")
	@RequestMapping(value = "form")
	public String form(MenuEntity menuEntity, Model model) {
		model.addAttribute("menuEntity", menuEntity);
		return "modules/wechat/menuEntityForm";
	}

	@RequiresPermissions("wechat:menuEntity:view")
	@RequestMapping(value = "save")
	@ResponseBody
	public AjaxJson save(MenuEntity menuEntity, Model model) {
        AjaxJson jo = new AjaxJson();
		try {
			if (!beanValidator(model, menuEntity)) {
                jo.setSuccess(false);
                jo.setMsg("数据校验失败,请重试!");
			} else {
                menuEntity.setTemplateid(menuEntity.getTemplateid().replace(",", ""));
                if (StringUtils.isBlank(menuEntity.getId())) {
                    menuEntity.setId(Identities.generateUUID());
                    menuEntityService.save(menuEntity);
                } else {
                    menuEntityService.update(menuEntity);
                }
            }
            msg = "保存菜单对象'" + menuEntity.getName() + "'成功";
            jo.setMsg(msg);
		} catch (Exception e) {
			e.printStackTrace();
            jo.setSuccess(false);
            jo.setMsg("操作失败,请联系管理员");
		}
		return jo;
	}
	
	@RequiresPermissions("wechat:menuEntity:view")
	@RequestMapping(value = "delete")
    @ResponseBody
	public AjaxJson delete(String id, RedirectAttributes redirectAttributes) {
        AjaxJson jo = new AjaxJson();
        if (StringUtils.isNotBlank(id)) {
            menuEntityService.delete(id);
            jo.setMsg("删除公众号成功");
        } else {
            jo.setSuccess(false);
            jo.setMsg("参数错误,删除失败");
        }
        return jo;
	}

    /**
     * 同步微信菜单
     * @param request
     * @return
     */
    @RequiresPermissions("wechat:menuEntity:view")
    @RequestMapping(value = "syncMenu")
    @ResponseBody
    public AjaxJson syncMenu(HttpServletRequest request){
        AjaxJson jo = new AjaxJson();
        //获取公众号ID
        String accountId = request.getParameter("accountId");
        if (StringUtils.isBlank(accountId)) {
            jo.setSuccess(false);
            jo.setMsg("参数错误");
        }
        WeixinAccount account = accountService.get(accountId);
        if (account == null) {
            jo.setSuccess(false);
            jo.setMsg("无该微信账号信息");
        }
        Map<String, String> retMap = menuEntityService.syncMenu(account);
        if (retMap != null) {
            if ("success".equals(retMap.get("ec"))) {
                jo.setSuccess(true);
            } else {
                jo.setSuccess(false);
            }
            jo.setMsg(retMap.get("em"));
        } else {
            jo.setSuccess(false);
            jo.setMsg("菜单同步失败");
        }
        return jo;
    }

    @RequiresPermissions("wechat:menuEntity:view")
    @RequestMapping(value = "uploadMenu")
    @ResponseBody
    public AjaxJson uploadMenu(HttpServletRequest request) {
        AjaxJson jo = new AjaxJson();
        //获取公众号ID
        String accountId = request.getParameter("accountId");
        if (StringUtils.isBlank(accountId)) {
            jo.setSuccess(false);
            jo.setMsg("参数错误");
        }
        WeixinAccount account = accountService.get(accountId);
        if (account == null) {
            jo.setSuccess(false);
            jo.setMsg("无该微信账号信息");
        }
        Map<String, String> retMap = menuEntityService.uploadMenu(account.getId());
        if (retMap != null) {
            if ("success".equals(retMap.get("ec"))) {
                jo.setSuccess(true);
            } else {
                jo.setSuccess(false);
            }
            jo.setMsg(retMap.get("em"));
        } else {
            jo.setSuccess(false);
            jo.setMsg("创建失败");
        }
        return jo;
    }

}
